#!/usr/bin/env python
import traceback
import platform
import cProfile
from player_submission import OpenMoveEvalFn, CustomEvalFn, CustomPlayer
from isolation import Board, game_as_text
from test_players import RandomPlayer, HumanPlayer
from custom_min_max_player import CustomPlayerMinMax
from timeit import  repeat
import random

if platform.system() != 'Windows':
   import resource
from time import time, sleep

win_times = 0
total_games = 10
time_cost = []
def single_run():
    global win_times
    try:
        #r = CustomPlayerMinMax()
        p1 = CustomPlayer(search_depth = 30)
        p2 = CustomPlayerMinMax(search_depth = 2)
        #h = RandomPlayer()
        # r = CustomPlayer( search_depth = 4)
        # h = CustomPlayerMinMax( search_depth = 2)
        #h = CustomPlayer()
        game = Board(p1, p2, 7, 7)
        ran_x1 = random.randint(0,6)
        ran_y1 = random.randint(0,6)
        ran_x2 = random.randint(0,6)
        ran_y2 = random.randint(0,6)
        while ran_x1 == ran_x2 and ran_y1 == ran_y2 :
            ran_x2 = random.randint(0,6)
            ran_y2 = random.randint(0,6)
        game.__board_state__[ran_x1][ran_y1] = "Q1"
        game.__board_state__[ran_x2][ran_y2] = "Q2"
        game.__last_queen_move__ = {
            game.__queen_1__: (ran_x1,ran_y1,False),
            game.__queen_2__: (ran_x2,ran_y2,False),
        }
        output_b = game.copy()
        winner, move_history, termination = game.play_isolation(time_limit=10000, print_moves=False)
        print "\n\n==========================================================\n"
        print output_b .print_board()
        print "\n",winner," has won. Reason: ", termination
        if winner == game.__queen_1__:
            win_times+=1

        # Uncomment to see game
        # print game_as_text(winner, move_history, termination, output_b)
    except NotImplementedError:
        print 'CustomPlayer Test: Not Implemented'
    except:
        print 'CustomPlayer Test: ERROR OCCURRED'
        print traceback.format_exc()


def do_test():
    global time_cost
    time_cost = repeat("single_run()", "from __main__ import single_run", number=1, repeat=total_games)


def main():

    """Example test you can run
    to make sure your AI does better
    than random."""
    print ""
    cProfile.run("do_test()")
    print "\nFirst player win rate:", win_times*1.0/total_games
    print "\neverage time cost:", sum(time_cost)/total_games, "s"

if __name__ == "__main__":
    main()
